﻿using jinmaMesProxy.Excep;
using static Azure.Core.HttpHeader;

namespace jinmaMesProxy
{
    public static class ServiceLoader
    {
        public static void InitHttpServiceProvider(IServiceProvider httpServiceProvider)
        {
            if (httpServiceProvider == null)
                throw new Exception("初始化ServiceProvider失败");
            HttpServiceProvider = httpServiceProvider;
        }
        internal static IServiceProvider? HttpServiceProvider { get; private set; }
        public static T GetService<T>()
        {
            var httpContext = HttpServiceProvider.GetRequiredService<IHttpContextAccessor>()?.HttpContext;
            try
            {
                return httpContext!.RequestServices.GetService<T>();
            }
            catch (Exception ex)
            {
                throw new MyException(ex);
            }
        }
        public static HttpContext GetHttpContext()
        {
            try
            {
                var httpContext = HttpServiceProvider!.GetRequiredService<IHttpContextAccessor>().HttpContext;
                return httpContext;
            }
            catch (Exception ex)
            {
                Logger.Err(ExceptionUtil.FormatExceptionInfo(ex));
                throw ex;
            }
        }
    }
}
